#!/usr/bin/env python3

import urllib.request
import urllib.parse
import json
from api import ApiService

token = 'd096fa52dc330f6871c4eef894992e38'

class DoubanNote():

    API_HOST = 'https://api.douban.com'
    AUTH_HOST = 'https://www.douban.com'

    TOKEN_URL = AUTH_HOST + '/service/auth2/token'
    AUTHORIZE_URL = AUTH_HOST + '/service/auth2/auth'


    def __init__(self, key, secret, redirect='', scope=''):
        self.redirect_uri = redirect
        self.scope = scope
        self.secret = secret

        if not token :
            #获取authorize code
            print(self.AUTHORIZE_URL + '?client_id=' + key + '&redirect_uri=' + redirect
                             + '&response_type=code&scope=' + scope)
            self.authorization_code = input('Enter the verification code:')

            #获取access token
            data = urllib.parse.urlencode({'client_id': key, 'client_secret': secret, 
                'redirect_uri': redirect, 'grant_type':'authorization_code', 'code': self.authorization_code})
            data = data.encode('utf-8')
            request = urllib.request.Request(self.TOKEN_URL)
            # adding charset parameter to the Content-Type header.
            request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
            f = urllib.request.urlopen(request, data)
            print(f.read().decode('utf-8'))

        request = urllib.request.Request(self.API_HOST + "/v2/user/~me")
        #request = urllib.request.Request(self.API_HOST + "/v2/note/user_created/61725334")
        request.add_header("Authorization", "Bearer " + token)
        f = urllib.request.urlopen(request)
        info = f.read().decode('utf-8')
        print(info)
        #obj = json.loads(info)
        #print(obj['loc_name'])

        ApiService(token).get(self.API_HOST + "/v2/user/~me")




if __name__ == '__main__':

    API_KEY = '09f9ec208d9a4d2c1dedc461a8cee784'
    API_SECRET = '0fccff82381019f7'
    REDIRECT_URI = 'http://www.doubannote.org/auth'
    SCOPE = 'douban_basic_common,community_basic_note,community_basic_user'

    client = DoubanNote(API_KEY, API_SECRET, REDIRECT_URI, SCOPE)
